<?php

namespace app\plus\controller;

use think\Controller;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use OSS\OssClient;
use think\Db;
use org\util\FileUtil;

class UploaderController extends Controller
{
    public function index()
    {
        header("Content-Type: text/html; charset=utf-8");
        $configJson = file_get_contents(EXTEND_PATH . "editor/config.json");
        $CONFIG     = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", $configJson), true);
        $action     = $_GET['action']; //动作节点
        $uid      = (int)$_GET['uid']; //使用场景
        $local      = isset($_GET['local']) && $_GET['local']==1 ? 1 : 0;
        switch ($action) {
            case 'config':
                $data = json_encode($CONFIG);
                break;
            /* 上传图片 */
            case 'uploadimage':
                /* 上传涂鸦 */
            case 'uploadscrawl':
                /* 上传视频 */
            case 'uploadvideo':
                /* 上传文件 */
            case 'uploadfile':
                $json = include(EXTEND_PATH . "editor/action_upload.php");
                //调用图片保存接口
                $uploadData = json_decode($json, true);
                //处理其他上传方式
                if ($uploadData['state'] == 'SUCCESS') {
                    $uploadType = config('base.upload_type');
                    if ($local == 0) {
                        switch ($uploadType) {
                            case 'qiniu':
                                //七牛云储存处理
                                $bucket    = config('base.qiniu_bucket');
                                $accessKey = config('base.qiniu_ak');
                                $secretKey = config('base.qiniu_sk');
                                $auth      = new Auth($accessKey, $secretKey);
                                $token     = $auth->uploadToken($bucket);
                                $uploadMgr = new UploadManager();
                                $filePath  = '.' . $uploadData['url'];
                                $key       = str_replace('/upload/', 'upload/', $uploadData['url']);
                                $uploadMgr->putFile($token, $key, $filePath);
                                $uploadData['url'] = config('base.upload_prefix') . $uploadData['url'];
                                //删除本地文件
                                FileUtil::unlinkFile($filePath);
                                break;
                            case 'alioss':
                                //阿里云存储处理
                                $accessKeyId     = config('base.alioss_ak');
                                $accessKeySecret = config('base.alioss_sk');
                                $endpoint        = config('base.alioss_endpoint');
                                $bucket          = config('base.alioss_bucket');
                                $ossClient       = new OssClient($accessKeyId, $accessKeySecret, $endpoint, true);
                                $filePath        = '.' . $uploadData['url'];
                                $key             = str_replace('/upload/', 'upload/', $uploadData['url']);
                                $ossClient->uploadFile($bucket, $key, $filePath);
                                $uploadData['url'] = config('base.upload_prefix') . $uploadData['url'];
                                //删除本地文件
                                FileUtil::unlinkFile($filePath);
                                break;
                        }
                        //插入附件表
                        $this->insertUpload($uid, $uploadData, 1);
                    }
                }
                $data = json_encode($uploadData);
                break;
            /* 列出图片 */
            case 'listimage':
                $data = $this->actionList($CONFIG, $uid);
                break;
            /* 列出文件 */
            case 'listfile':
                $data = $this->actionList($CONFIG, $uid);
                break;
            /* 抓取远程文件 */
            case 'catchimage':
                $json       = include(EXTEND_PATH . "editor/action_crawler.php");
                $uploadData = json_decode($json, true);
                if ($uploadData['state'] == 'SUCCESS') {
                    $uploadType = config('base.upload_type');
                    $dataList   = [];
                    if ($local == 0) {
                        switch ($uploadType) {
                            case 'qiniu':
                                //七牛云储存处理
                                $bucket    = config('base.qiniu_bucket');
                                $accessKey = config('base.qiniu_ak');
                                $secretKey = config('base.qiniu_sk');
                                $auth      = new Auth($accessKey, $secretKey);
                                $token     = $auth->uploadToken($bucket);
                                $uploadMgr = new UploadManager();
                                foreach ($uploadData['list'] as $v) {
                                    $filePath = '.' . $v['url'];
                                    $key      = str_replace('/upload/', 'upload/', $v['url']);
                                    $uploadMgr->putFile($token, $key, $filePath);
                                    $v['url']   = config('base.upload_prefix') . $v['url'];
                                    $dataList[] = $v;
                                    //删除本地文件
                                    FileUtil::unlinkFile($filePath);
                                }
                                break;
                            case 'alioss':
                                //阿里云存储处理
                                $accessKeyId     = config('base.alioss_ak');
                                $accessKeySecret = config('base.alioss_sk');
                                $endpoint        = config('base.alioss_endpoint');
                                $bucket          = config('base.alioss_bucket');
                                $ossClient       = new OssClient($accessKeyId, $accessKeySecret, $endpoint, true);
                                foreach ($uploadData['list'] as $v) {
                                    $filePath = '.' . $v['url'];
                                    $key      = str_replace('/upload/', 'upload/', $v['url']);
                                    $ossClient->putFile($bucket, $key, $filePath);
                                    $v['url']   = config('base.upload_prefix') . $v['url'];
                                    $dataList[] = $v;
                                    //删除本地文件
                                    FileUtil::unlinkFile($filePath);
                                }
                                break;
                        }
                        if ($dataList) {
                            $this->insertUpload($uid, $dataList, 2);
                        }
                    }
                }
                break;
            default:
                $data = json_encode([
                    'state' => '请求地址出错',
                ]);
                break;
        }

        /* 输出结果 */
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($_GET["callback"]) . '(' . $data . ')';
            } else {
                echo json_encode([
                    'state' => 'callback参数不合法',
                ]);
            }
        } else {
            echo $data;
        }
    }

    /**
     * 列出附件列表
     * @param $CONFIG
     * @param $utype
     * @return mixed
     */
    public function actionList($CONFIG, $uid)
    {
        /* 判断类型 */
        switch ($_GET['action']) {
            /* 列出文件 */
            case 'listfile':
                $allowFiles = $CONFIG['fileManagerAllowFiles'];
                break;
            /* 列出图片 */
            case 'listimage':
            default:
                $allowFiles = $CONFIG['imageManagerAllowFiles'];
        }
        $start        = $this->request->param('start');
        $size         = $this->request->param('size');
        $map['uid']   = $uid;
        $map['type']  = ['in', $allowFiles];
        //分页取数据
        $count = Db::table('attachment')->where($map)->count();
        $list  = Db::table('attachment')->field('url,mtime,upload_type')
            ->order('id desc')
            ->where($map)
            ->limit($start, $size)->select();
        return json_encode([
            "state" => "SUCCESS",
            "list"  => $list,
            "start" => $start,
            "total" => $count,
        ], true);
    }

    /**
     * 保存上传记录
     */
    private function insertUpload($uid, $data, $insertType = 1)
    {
        $upload_type = config('base.upload_type');
        if ($insertType == 1) { //单条插入
            $upload['uid']         = $uid;
            $upload['group_id']    = 0;
            $upload['original']    = $data['original'];
            $upload['size']        = $data['size'];
            $upload['type']        = $data['type'];
            $upload['title']       = $data['title'];
            $upload['upload_type'] = $upload_type;
            $upload['url']         = $data['url'];
            $upload['mtime']       = time();
            Db::table('attachment')->insert($upload);
        } else { //批量插入
            foreach ($data as $v) {
                $dataList[] = [
                    'uid'         => $uid,
                    'group_id'    => 0,
                    'original'    => $v['original'],
                    'size'        => $v['size'],
                    'type'        => $v['type'],
                    'title'       => $v['title'],
                    'upload_type' => $upload_type,
                    'url'         => $v['url'],
                    'mtime'       => time(),
                ];
            }
            Db::table('attachment')->insertAll($dataList);
        }
    }
}